package com.yiren.dbaa.module.exam.api.impl;

import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.enums.CarTypeEnum;
import com.yiren.backstage.config.enums.SiteConfigCodeEnum;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.bean.LinePointBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.enums.CarStateNameEnum;
import com.yiren.backstage.currency.enums.CarStateValueEnum;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.dbaa.R;
import com.yiren.dbaa.module.exam.api.IExamViewApi;
import com.yiren.dbaa.module.practice_set.line.contract.BaiduMapContract;
import com.yiren.dbaa.module.practice_set.line.model.BaiduMapModel;
import com.yiren.dbaa.util.AccuracyPixelUtil;
import com.yiren.dbaa.util.CarBitmapUtil;
import com.yiren.dbaa.view.TrajectoryMapView;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe 考试页面高低精度地图处理实现类
 *
 * @author WRX
 * @date 2022/7/15
 */
public class ExamViewApiImpl implements IExamViewApi {

    public final float mapScaleWidth = 0.62f;    //显示地图和轨迹区域默认的宽高比例
    public final float mapScaleHeight = 0.72f;   //显示地图和轨迹区域默认的宽高比例

    private Activity activity;
    private BaiduMapContract.Model baiduMapModel;

    public ExamViewApiImpl(Activity activity) {
        this.activity = activity;
        baiduMapModel = new BaiduMapModel();
    }

    @Override
    public RelativeLayout.LayoutParams getMapRelativeParam(int scale) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        if (scale == 0) {
            params.width = 1;
            params.height = 1;
        } else {
            WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;         // 屏幕宽度（像素）
            int height = dm.heightPixels;       // 屏幕高度（像素）
            if (scale == 1) {
                params.width = (int) (width * mapScaleWidth);
                params.height = (int) (height * mapScaleHeight);
                params.leftMargin = (int) (width * (1 - mapScaleWidth) * 0.5);
                params.topMargin = (int) (height * (1 - mapScaleHeight) * 0.5);
            } else {
                params.leftMargin = 10;
                params.rightMargin = 10;
                params.topMargin = 10;
                params.bottomMargin = 10;
            }
        }
        return params;
    }

    @Override
    public TrajectoryMapView getGjdMapView(TrajectoryMapView mapView) {
        if (mapView == null) mapView = new TrajectoryMapView(activity);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mapView.setLayoutParams(params);
        mapView.setMapViewAttrs(false);
        mapView.setAccuracy(AccuracyPixelUtil.Accuracy_M7);
        mapView.setZOrderOnTop(true);
        return mapView;
    }

    @Override
    public TextureMapView getDjdMapView() {
        TextureMapView tmvMapView = new TextureMapView(activity);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        tmvMapView.setLayoutParams(params);
        return tmvMapView;
    }

    @Override
    public BaiduMap getBaiduMap(BaiduMap mBaiduMap, TextureMapView tmvMapView) {
        if (mBaiduMap != null) mBaiduMap.clear();
        mBaiduMap = baiduMapModel.getBaiduMap(tmvMapView);
        GpsInfoBean gpsInfo = GpsInfoBean.getInstance();
        if (null != gpsInfo) {
            MyLocationData locData = new MyLocationData.Builder().accuracy(gpsInfo.getRadius()).direction(gpsInfo.getDirection()).latitude(gpsInfo.getLatitude()).longitude(gpsInfo.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            LatLng ll = new LatLng(gpsInfo.getLatitude(), gpsInfo.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(20.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
        return mBaiduMap;
    }

    @Override
    public void drawBaiduMarker(LineInfoEntity lineInfo, BaiduMap mBaiduMap) {
        if (null == lineInfo || null == lineInfo.getLinePoints()) return;
        List<LatLng> points = new ArrayList<LatLng>();
        new Thread(() -> {
            for (int i = 0; i < lineInfo.getLinePoints().size(); i++) {
                LinePointBean linePoint = lineInfo.getLinePoints().get(i);
                LatLng p1 = new LatLng(linePoint.getLatitude(), linePoint.getLongitude());
                points.add(p1);
                List<LatLng> currentPoints = new ArrayList<LatLng>();
                if (points.size() >= 1) {
                    LatLng lastPoint = points.get(points.size() - 1);
                    currentPoints.add(lastPoint);
                    currentPoints.add(p1);
                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.map_point_red);
                    OverlayOptions optionImage = new MarkerOptions().position(lastPoint).icon(bitmap);
                    if (null != linePoint.getProjectInfo() && null != linePoint.getProjectInfo().getName()) {
                        OverlayOptions textOption = new TextOptions().fontSize(30).fontColor(0xAAFF0000).text((i + 1) + "." + linePoint.getProjectInfo().getName()).rotate(-30).position(lastPoint);
                        if (mBaiduMap != null) {
                            mBaiduMap.addOverlay(textOption);
                        }
                    }
                    if (mBaiduMap != null) {
                        mBaiduMap.addOverlay(optionImage);
                    }
                }
            }
        }).start();
    }

    @Override
    public void updateLocationInfo(GpsInfoBean gpsInfo, BaiduMap mBaiduMap) {
        if (gpsInfo.isLocationSuccess(activity) && mBaiduMap != null) {
            // map view 销毁后不在处理新接收的位置
            MyLocationData locData = new MyLocationData.Builder().accuracy(gpsInfo.getBearing())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(gpsInfo.getDirection()).latitude(gpsInfo.getLatitude()).longitude(gpsInfo.getLongitude()).build();
            if (null != mBaiduMap) mBaiduMap.setMyLocationData(locData);
            LatLng ll = new LatLng(gpsInfo.getLatitude(), gpsInfo.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            if (null != mBaiduMap) {
                mBaiduMap.animateMapStatus(u);
            }
        }
    }

    @Override
    public void carStateImageSwitch(LinearLayout llExamMain, CarStateBean carState) {
        // 左转向灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.LEFT_LIGHT, carState.getLeftLight() == CarStateValueEnum.OPEN, carState.getLeftLight());
        // 右转向灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.RIGHT_LIGHT, carState.getRightLight() == CarStateValueEnum.OPEN, carState.getRightLight());
        // 远光灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.DISTANCE_LIGHT, carState.getDistanceLight() == CarStateValueEnum.OPEN, carState.getDistanceLight());
        // 近光灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.PASSING_LIGHT, carState.getPassingLight() == CarStateValueEnum.OPEN, carState.getPassingLight());
        // 警示灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.CAUTION_LIGHT, carState.getCautionLight() == CarStateValueEnum.OPEN, carState.getCautionLight());
        // 行车灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.DRIVING_LAMP, carState.getDrivingLamp() == CarStateValueEnum.OPEN, carState.getDrivingLamp());
        // 雾灯
        carStateImageSwitch(llExamMain, CarStateNameEnum.FOGLIGHT, carState.getFoglight() == CarStateValueEnum.OPEN, carState.getFoglight());
        // 安全带
        carStateImageSwitch(llExamMain, CarStateNameEnum.SAFETY_BELT, carState.getSafetyBelt() == CarStateValueEnum.HITCH, carState.getSafetyBelt());
        // 车门
        carStateImageSwitch(llExamMain, CarStateNameEnum.CAR_DOOR, carState.getCarDoor() == CarStateValueEnum.OPEN, carState.getCarDoor());
        // 脚刹
        carStateImageSwitch(llExamMain, CarStateNameEnum.FOOT_BRAKE, carState.getFootBrake() == CarStateValueEnum.STEP_ON, carState.getFootBrake());
        // 喇叭
        carStateImageSwitch(llExamMain, CarStateNameEnum.HORN, carState.getHorn() == CarStateValueEnum.OPEN, carState.getHorn());
        // 手刹
        carStateImageSwitch(llExamMain, CarStateNameEnum.PARKING_BRAKE, carState.getParkingBrake() == CarStateValueEnum.COCKING, carState.getParkingBrake());
        // 离合
        carStateImageSwitch(llExamMain, CarStateNameEnum.SEPARATION_REUNION, carState.getSeparationReunion() == CarStateValueEnum.STEP_ON, carState.getSeparationReunion());
    }

    /**
     * 车辆状态图标切换
     */
    private void carStateImageSwitch(LinearLayout llExamMain, CarStateNameEnum carStateName, boolean isChecked, CarStateValueEnum carStateCode) {
        if (llExamMain != null) {
            View view = llExamMain.findViewWithTag(carStateName.toString());
            if (view instanceof RadioButton) {
                RadioButton rb = (RadioButton) view;
                if (rb != null) {  //设置全部信号的选中状态
                    rb.setText(carStateCode.getName());
                    rb.setChecked(isChecked);
                }
            }
        }
    }

    @Override
    public int setLightCarInfo(TrajectoryMapView mapView, CarStateBean carState) {
        String currentCar;
        int dg = 0;
        if (mapView != null) {
            if (carState.getFootBrake() == CarStateValueEnum.STEP_ON) {
                if (carState.getCautionLight() == CarStateValueEnum.OPEN) {
                    dg = 9;
                    currentCar = CarBitmapUtil.CAR_SS_SCD;
                } else if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                    dg = 10;
                    currentCar = CarBitmapUtil.CAR_ZZ_SCD;
                } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                    dg = 11;
                    currentCar = CarBitmapUtil.CAR_YZ_SCD;
                } else if (carState.getPassingLight() == CarStateValueEnum.OPEN) {
                    dg = 12;
                    currentCar = CarBitmapUtil.CAR_JG_SCD;
                } else if (carState.getDistanceLight() == CarStateValueEnum.OPEN) {
                    dg = 13;
                    currentCar = CarBitmapUtil.CAR_YG_SCD;
                } else {
                    dg = 7;
                    currentCar = CarBitmapUtil.CAR_SCD;
                }
            } else if (carState.getCautionLight() == CarStateValueEnum.OPEN) {
                if (carState.getDistanceLight() == CarStateValueEnum.OPEN) {
                    dg = 8;
                    currentCar = CarBitmapUtil.CAR_YG_SSD;
                } else {
                    dg = 5;
                    currentCar = CarBitmapUtil.CAR_JSD;
                }
            } else if (carState.getLeftLight() == CarStateValueEnum.OPEN) {
                dg = 1;
                currentCar = CarBitmapUtil.CAR_ZZD;
            } else if (carState.getRightLight() == CarStateValueEnum.OPEN) {
                dg = 2;
                currentCar = CarBitmapUtil.CAR_YZD;
            } else if (carState.getDistanceLight() == CarStateValueEnum.OPEN) {
                dg = 3;
                currentCar = CarBitmapUtil.CAR_YGD;
            } else if (carState.getPassingLight() == CarStateValueEnum.OPEN) {
                dg = 4;
                currentCar = CarBitmapUtil.CAR_JGD;
            } else if (carState.getFoglight() == CarStateValueEnum.OPEN) {
                dg = 6;
                currentCar = CarBitmapUtil.CAR_WD;
            } else {
                currentCar = CarBitmapUtil.CAR_NORMAL;
            }
            //显示那种车辆模型
            if (currentCar == CarBitmapUtil.CAR_YG_SSD) {
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, CarBitmapUtil.CAR_YGD));
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, currentCar));
            } else if (currentCar == CarBitmapUtil.CAR_SS_SCD || currentCar == CarBitmapUtil.CAR_YZ_SCD || currentCar == CarBitmapUtil.CAR_ZZ_SCD) {
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, CarBitmapUtil.CAR_SCD));
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, currentCar));
            } else if (currentCar == CarBitmapUtil.CAR_JSD || currentCar == CarBitmapUtil.CAR_ZZD || currentCar == CarBitmapUtil.CAR_YZD) {
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, currentCar));
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, CarBitmapUtil.CAR_NORMAL));
            } else {
                mapView.setBitmap(CarBitmapUtil.getBitmap(activity, currentCar));
            }
        }
        return dg;
    }

    @Override
    public void setConditionMileage(TextView tv, float mileage) {
        String txt;
        CarTypeEnum carType = LoadConfigApi.loadSignalSourceConfig(activity).getCarType();
        switch (carType) {
            case C2_MODEL:
                txt = "大于" + SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L26.toString()) + "码：";
                break;
            default:
                int chooseValueC1 = (int) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L21.toString());
                if (chooseValueC1 == 1)
                    txt = "大于" + SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L22.toString()) + "码：";
                else if (chooseValueC1 == 2 || chooseValueC1 == 3)
                    txt = "1、2档：";
                else
                    txt = SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L23.toString()) + "档以上大于" + SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L24.toString()) + "码：";
                break;
        }
        txt += ((mileage <= 999) ? (StringUtil.format(mileage, "#") + "M") : (StringUtil.format((mileage / 1000), "#.##") + "KM"));
        tv.setText(txt);
    }
}
